/**
 * ======================================================================
 * 插件作用：修改 config/vite/plugins/components/* 任意扩展配置自动重启vite
 * ----------------------------------------------------------------------
 * Author: 曹操<pgcao@qq.com>(https://gitee.com/pgcao) License MIT
 * ======================================================================
 */
import type { Plugin } from 'vite'
import { normalizePath } from 'vite'
import { resolve } from 'path'
import fs from 'fs'

export default (options?: viteUserOptions): viteUserPlugins => {
  const restartVite = (): Plugin => {
    let root = process.cwd()
    let timer: NodeJS.Timeout = null
    const changeConfigFile = (path2: string) => {
      const time = new Date()
      try {
        fs.utimesSync(path2, time, time)
      } catch (err) {
        fs.closeSync(fs.openSync(path2, 'w'))
      }
    }
    return {
      name: 'vite-plugin-auto-restart',
      apply: 'serve',
      configureServer({ watcher }) {
        const checkReload = (eventName: string, pathname: string) => {
          let isReload = false
          if (normalizePath(pathname).includes('src/assets/globals.scss')) {
            if (['add', 'unlink'].includes(eventName)) {
              isReload = true
            }
          } else if (normalizePath(pathname).includes('config/vite/plugins/components')) {
            if (['add', 'change', 'unlink'].includes(eventName)) {
              isReload = true
            }
          }
          if (isReload) {
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
              if (fs.existsSync('vite.config.js')) {
                changeConfigFile(resolve(root, 'vite.config.js'))
              } else if (fs.existsSync('vite.config.ts')) {
                changeConfigFile(resolve(root, 'vite.config.ts'))
              }
            }, 500)
          }
        }
        watcher.on('all', checkReload)
      }
    }
  }

  return {
    plugins: restartVite()
  }
}
